package com.easy.common.util;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSignerUtil;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JWTUtil {

    /**
     * SECRET_KEY:签名,重启服务时会动态生成
     */
    public static final String SECRET_KEY = "EASY";
    //token有效时间
    private static final long EXPIRATION = 86400000; // 24小时
    //生成token的方法
    public static String generateToken(Map map) {
        return JWT.create().setExpiresAt(new Date(System.currentTimeMillis()+EXPIRATION))
                .setKey(SECRET_KEY.getBytes())
                .sign();
//        return Jwts.builder()
//                .setSubject(username)
//                .claim("roles", roles)
//                .setIssuedAt(new Date())
//                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
//                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
//                .compact();
    }

    public static Object parseToken(String token) {
        JWT jwt=cn.hutool.jwt.JWTUtil.parseToken(token);
        return jwt;
//        return Jwts.parser()
//                .setSigningKey(SECRET_KEY)
//                .parseClaimsJws(token)
//                .getBody();
    }
    public static boolean verifyToken(String token){
        if(!cn.hutool.jwt.JWTUtil.verify(token, SECRET_KEY.getBytes())){
            throw new RuntimeException("签名异常");
        }
        try{
            JWTValidator.of(token).validateDate();
        }catch (Exception e){
            throw new RuntimeException("签名过期");
        }
        return true;
    }

    public static void main(String[] args){
        Map map=new HashMap();
        map.put("name","张三");
        //String token=generateToken(map);
        String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3NDQyNjkyNTB9.TqtIL8tjzE_t3KMG_C_XPLOsSPiE-VjSo11kH8gY7CM";
        System.out.println(token);
        System.out.println(parseToken(token));
        System.out.println(verifyToken(token));
    }
}
